// 动画性能优化工具

// 使用 requestAnimationFrame 优化动画
export const animate = (callback) => {
    let animationFrameId;
    const animate = () => {
        callback();
        animationFrameId = requestAnimationFrame(animate);
    };
    animationFrameId = requestAnimationFrame(animate);
    return () => cancelAnimationFrame(animationFrameId);
};

// 使用 transform 和 opacity 优化动画性能
export const optimizeAnimation = (element) => {
    if (element) {
        element.style.transform = 'translateZ(0)';
        element.style.willChange = 'transform, opacity';
    }
};

// 延迟加载动画
export const lazyLoadAnimation = (element, animationClass, delay = 0) => {
    setTimeout(() => {
        if (element) {
            element.classList.add(animationClass);
            optimizeAnimation(element);
        }
    }, delay);
};

// 批量处理动画
export const batchAnimate = (elements, animationClass, staggerDelay = 50) => {
    elements.forEach((element, index) => {
        lazyLoadAnimation(element, animationClass, index * staggerDelay);
    });
};

// 检测动画性能
export const checkAnimationPerformance = () => {
    const fps = [];
    let lastTime = performance.now();
    
    const check = () => {
        const currentTime = performance.now();
        const delta = currentTime - lastTime;
        
        if (delta >= 1000) {
            const currentFps = Math.round((1000 * fps.length) / delta);
            console.log(`当前FPS: ${currentFps}`);
            
            if (currentFps < 30) {
                console.warn('动画性能较低，建议优化');
            }
            
            fps.length = 0;
            lastTime = currentTime;
        }
        
        fps.push(currentTime);
        requestAnimationFrame(check);
    };
    
    requestAnimationFrame(check);
};

// 优化滚动性能
export const optimizeScroll = (element) => {
    if (element) {
        element.style.overflow = 'auto';
        element.style.webkitOverflowScrolling = 'touch';
        element.style.backfaceVisibility = 'hidden';
    }
};

// 动画节流
export const throttle = (fn, delay = 100) => {
    let timer = null;
    let lastTime = 0;
    
    return function (...args) {
        const currentTime = Date.now();
        
        if (currentTime - lastTime >= delay) {
            fn.apply(this, args);
            lastTime = currentTime;
        } else if (!timer) {
            timer = setTimeout(() => {
                fn.apply(this, args);
                lastTime = Date.now();
                timer = null;
            }, delay);
        }
    };
};

// 动画防抖
export const debounce = (fn, delay = 100) => {
    let timer = null;
    
    return function (...args) {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(this, args);
        }, delay);
    };
}; 